# -*- coding: utf-8 -*-
__author__ = 'sunnychou'
__date__ = '2019/9/18 9:50'

'''
k3的基础表导入主入口
'''
from collections import defaultdict

from common.excel_helper import XLSXBooker, ExcelReader

from k3_data_report.business.cgtj_db import Cgtj
from k3_data_report.config import *
from k3_data_report.utils import *
from common.orm_helper import *

def  check_base_tb_store():
    '''
    检测基础报表在db中是否存在，如果不存在，则插入
    :return:
    '''
    basewj_dict  = get_wj(k3_base_table_fields['check_sql']["checkwj_sql"])
    base_wj_check_set = set()
    for key in basewj_dict.keys():
        (type, excel_file, insert_time, check_flag) = basewj_dict[key]
        if check_flag == "Y":   #已经处理过了，跳过
            g_wlogger.winfo(f"the scan file:{excel_file} is already processed")
            continue
        k3_base_scan_dict = k3_base_table_fields['k3_base_scan']
        print(f"excel_file：{excel_file}")
        file_infos = charge_excel_pretype(excel_file)
        if file_infos == None:
            g_wlogger.warning(f"the scan file:{excel_file} charge_excel_pretype has error.")
            continue
        (file_type, file_date) = file_infos
        scan_file_tuple = k3_base_scan_dict.get(file_type, None)
        print(f"file_type:{file_type}, file_date:{file_date},scan_file_tuple:{scan_file_tuple} ")
        if scan_file_tuple == None:
            g_wlogger.warning(f"the scan file:{file_type}-{file_date}.xls,  not exist or define")
            continue
        (base_tb_name, sheet_name, insert_sql_key, optype)  = scan_file_tuple

        process_func = k3_base_table_fields["k3_jichu_tb"][insert_sql_key]
        check_base_tbsql = k3_base_table_fields['check_sql']['insert_check_sql'] % (base_tb_name, file_date)
        check_exist_dict = Cgtj.check_cf(check_base_tbsql)
        if len(check_exist_dict) == 0:    #没有记录，插入，并更新
            insert_info = f"插入信息：excel 文件:{excel_file}, 日期：{insert_time}"
            print(insert_info)
            g_wlogger.wdebug(insert_info)
            #LOCAL_DIR_SCAN = 1 --- 扫描本地文件目录
            #LOCAL_DIR_SCAN = 0 --- 扫描文件上传目录
            full_path_file = f"{BASE_DRP_TABLE_DIR}" + f"\\{type}\\" + excel_file if LOCAL_DIR_SCAN else    f"{UPLOAD_TABLE_DIR}\\" + excel_file
            if optype == 1:
                insert_sql = process_func
                insert_k3_dp_tb(full_path_file, sheet_name, insert_sql, insert_time)   #process_func等同于sql
            else:
                if not process_func(full_path_file,sheet_name):
                    continue
            update_k3_dp_tb(key, insert_time)
        else:
            alinsert_info = f"该月份{file_date}数据表:{excel_file} 已经插入!"
            #print(alinsert_info)
            g_wlogger.winfo(alinsert_info)
    return True


def scan_local_base_tbfiles():
    '''
    扫描文件夹，保存到数据库表k3wjsm中
    :return:
    '''
    try:
        Scanfiles.file_name(BASE_DRP_TABLE_DIR)
    except Exception as e:
        g_wlogger.werror(f"scan_base_filedir_store has error {e}")



def base_data_table_import():
    '''
    扫描上传文件夹，进行基础数据表导入
    :return:
    '''
    # orm数据库表同步
    create_orm_db()
    # 扫描本地文件
    scan_local_base_tbfiles()
    check_base_tb_store()



def cal_the_month_data_report(the_month):
    '''
    计算指定月份报表数据
    :param the_month: 指定月份
    :return:
    '''
    try:
        for mkey in MONTH_PROCESS_DICT.keys():
            process_func = MONTH_PROCESS_DICT[mkey]
            if not process_func(the_month):
                continue
            g_wlogger.winfo(f"cal_the_month_data_report process the key:{mkey}, month:{the_month} success.")
        g_wlogger.winfo(f"all cal_the_month_data_report process month:{the_month} finish done ! ")
        return True
    except Exception as e:
        g_wlogger.werror(f"cal_the_month_data_report has error with month:{the_month} ")
        return False


def cal_this_month_data_report():
    '''
    自动计算本月，并计算月报表
    :return:
    '''
    from common.utils import FVDateTime, get_month
    this_month = get_month(FVDateTime().to_dict()['this_month_start'])
    cal_the_month_data_report(this_month)


if __name__ == "__main__":
    #处理基础表
    base_data_table_import()

    #处理所有的月份
    mouth_list=['2018-01','2018-02','2018-03','2018-04','2018-05','2018-06','2018-07','2018-08','2018-09','2018-10','2018-11','2018-12',
            '2019-01','2019-02','2019-03','2019-04','2019-05','2019-06','2019-07','2019-08']

    [cal_the_month_data_report(month) for month in mouth_list]







